package api

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"zsc-boot/app/system_layer/model"
	"zsc-boot/app/system_layer/model/request"
	"zsc-boot/app/system_layer/service"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

var (
	ServiceDepartmentApi     = new(serviceDepartmentApi)
	serviceDepartmentService = service.ServiceDepartmentService
)

type serviceDepartmentApi struct {
}

// CreateServiceDepartment 创建组织
func (s *serviceDepartmentApi) CreateServiceDepartment(ctx *gin.Context) {
	var serviceDepartment model.ServiceDepartment
	_ = ctx.BindJSON(&serviceDepartment)
	if err := serviceDepartmentService.CreateDepartment(serviceDepartment); err != nil {
		core.GetLogger().Error("操作失败", zap.Error(err))
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// DeleteServiceDepartment 删除组织
func (s *serviceDepartmentApi) DeleteServiceDepartment(ctx *gin.Context) {
	var serviceDepartment model.ServiceDepartment
	_ = ctx.BindJSON(&serviceDepartment)
	if err := serviceDepartmentService.DeleteServiceDepartment(serviceDepartment); err != nil {
		core.GetLogger().Error("操作失败", zap.Error(err))
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// UpdateServiceDepartment 更新组织
func (s *serviceDepartmentApi) UpdateServiceDepartment(ctx *gin.Context) {
	var serviceDepartment model.ServiceDepartment
	_ = ctx.BindJSON(&serviceDepartment)
	if err := serviceDepartmentService.UpdateServiceDepartment(serviceDepartment); err != nil {
		core.GetLogger().Error("操作失败", zap.Error(err))
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// GetServiceDepartment 查询组织详情
func (s *serviceDepartmentApi) GetServiceDepartment(ctx *gin.Context) {
	var id core.GetById
	_ = ctx.BindQuery(&id)
	if err, data := serviceDepartmentService.GetServiceDepartment(id.ID); err != nil {
		core.GetLogger().Error("操作失败", zap.Error(err))
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, data)
	}
}

// GetServiceDepartmentList 查询组织列表
func (s *serviceDepartmentApi) GetServiceDepartmentList(ctx *gin.Context) {
	var pageInfo request.ServiceDepartmentSearch
	_ = ctx.BindQuery(&pageInfo)

	userId := service.GetUserID(ctx)
	data, err := orm.Detail[model.ServiceUser](userId, "Role")
	if err != nil {
		web.FailResponse(ctx, err, err.Error())
		return
	}

	if err, list, total := serviceDepartmentService.GetServiceDepartmentList(pageInfo, data); err != nil {
		core.GetLogger().Error("操作失败", zap.Error(err))
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessListResponse(ctx, list, total, pageInfo.Page, pageInfo.PageSize)
	}
}
